/*
 * Copyright Aduna (http://www.aduna-software.com/) (c) 1997-2008.
 *
 * Licensed under the Aduna BSD-style license.
 */
package edu.tju.rdfbase.store.helpers;

import java.util.HashSet;
import java.util.Set;

import edu.tju.rdfbase.store.NotifyingStore;
import edu.tju.rdfbase.store.NotifyingStoreConnection;
import edu.tju.rdfbase.store.StoreChangedEvent;
import edu.tju.rdfbase.store.StoreChangedListener;
import edu.tju.rdfbase.store.StoreException;

/**
 * This class extends {@link StoreBase} with {@link NotifyingStore} support.
 * 
 * @author Herko ter Horst
 * @author jeen
 * @author Arjohn Kampman
 * @author James Leigh
 */
public abstract class NotifyingStoreBase extends StoreBase implements NotifyingStore {

	/*-----------*
	 * Variables *
	 *-----------*/

	/**
	 * Objects that should be notified of changes to the data in this Store.
	 */
	private Set<StoreChangedListener> storeChangedListeners = new HashSet<StoreChangedListener>(0);

	/*---------*
	 * Methods *
	 *---------*/

	@Override
	public NotifyingStoreConnection getConnection()
		throws StoreException
	{
		return (NotifyingStoreConnection)super.getConnection();
	}

	@Override
	protected abstract NotifyingStoreConnection getConnectionInternal()
		throws StoreException;

	public void addStoreChangedListener(StoreChangedListener listener) {
		synchronized (storeChangedListeners) {
			storeChangedListeners.add(listener);
		}
	}

	public void removeStoreChangedListener(StoreChangedListener listener) {
		synchronized (storeChangedListeners) {
			storeChangedListeners.remove(listener);
		}
	}

	/**
	 * Notifies all registered StoreChangedListener's of changes to the contents
	 * of this Store.
	 */
	public void notifyStoreChanged(StoreChangedEvent event) {
		synchronized (storeChangedListeners) {
			for (StoreChangedListener l : storeChangedListeners) {
				l.storeChanged(event);
			}
		}
	}
}
